<!--
 * @Author: 谢陈洁
 * @Date: 2025-07-09 09:20:08
 * @LastEditors: 谢陈洁
 * @LastEditTime: 2025-07-23 16:12:07
 * @Description: file content
-->
<template>
  <div ref="chartRef" :style="{ width: width, height: height }"></div>
</template>

<script setup lang="ts">
  import * as echarts from 'echarts'
  import type { EChartsOption } from 'echarts'

  // 使用withDefaults函数结合类型定义和默认值
  const props = withDefaults(
    defineProps<{
      option: EChartsOption
      width?: string
      height?: string
    }>(),
    {
      width: '100%',
      height: '400px'
    }
  )

  const chartRef = ref<HTMLDivElement>(null)
  let chartInstance: echarts.ECharts | null = null

  onMounted(() => {
    if (chartRef.value) {
      chartInstance = echarts.init(chartRef.value)
      chartInstance.setOption(props.option)

      // 响应窗口大小变化
      window.addEventListener('resize', handleResize)
    }
  })

  watch(
    () => props.option,
    (newOption: EChartsOption) => {
      chartInstance?.setOption(newOption)
    },
    { deep: true }
  )

  const handleResize = () => {
    chartInstance?.resize()
  }

  // 组件卸载时销毁图表实例
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    chartInstance?.dispose()
    chartInstance = null
  })
</script>
